package org.example.Swing.handler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JOptionPane;

import org.example.Dao.userDao;
import org.example.Entity.Student;
import org.example.Swing.xiangmu.login.LoginView;
import org.example.Swing.xiangmu.login.MainStuView;
import org.example.Swing.xiangmu.login.MainView;
import org.example.Swing.xiangmu.login.ZhuceView;
import org.example.Utils.MybatisUtils;
import org.example.controller.GradeController;
import org.example.controller.UserOne;

public class LoginHandler extends KeyAdapter implements ActionListener {
	
	private LoginView loginView;
	public LoginHandler(LoginView loginView) {
		this.loginView = loginView;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		JButton jButton= (JButton) e.getSource();
		String text = jButton.getText();
		if ("注册".equals(text)) {
			new ZhuceView();
			loginView.dispose();
		}else if ("登录".equals(text)) {
			login();
		}
	}
	//登录事件及条件判断
	private void login() {
		String user=loginView.getUserTxt().getText();
		char[] chars=loginView.getPwdField().getPassword();
		String pwd=new String(chars);
		UserOne userOne=new UserOne();
		int result=userOne.selectStudent(user);
		if(result==1){
			if (user!=null&&pwd!=null) {
				UserOne user1 = new UserOne();
				if (user.isEmpty() && pwd.isEmpty()) {
					JOptionPane.showMessageDialog(loginView, "请输入账号密码后在登录！");
				} else {
					int login = user1.login(user, pwd);
					if (login > 0) {
						JOptionPane.showMessageDialog(loginView, "登录成功");
						new MainView();
						loginView.dispose();
					} else {
						JOptionPane.showMessageDialog(loginView, "登录失败");
					}
				}
			}else {
				JOptionPane.showMessageDialog(loginView, "请输入用户名和密码！");

			}
		} else if (result==2) {
			String name=loginView.getUserTxt().getText();
			UserOne user2 = new UserOne();
			int login = user2.login(user, pwd);
			if (login > 0) {
				JOptionPane.showMessageDialog(loginView, "登录成功");
				new MainStuView(name);
				loginView.dispose();
			} else {
				JOptionPane.showMessageDialog(loginView, "登录失败");
			}
		}else {
			JOptionPane.showMessageDialog(loginView, "该用户未注册");
		}
	}

	
	@Override
	public void keyPressed(KeyEvent e) {
		if (KeyEvent.VK_ENTER== e.getKeyCode()) {
			login();
		}
	}
}
